<template>
	<view>
		<view class="cu-card">
			<view class="cu-item ship">
				<radio-group @change="chooseShpping">
					<label class="margin-right-sm">
						<radio class='red margin-right-sm checked' :checked="bookingOrder.shippingMethod===shippingMethodForExpress" :value="shippingMethodForExpress"></radio>商家派送
					</label>
					<label>
						<radio class='red margin-right-sm' :checked="bookingOrder.shippingMethod===shippingMethodForSelf" :value="shippingMethodForSelf"></radio>自提
					</label>
				</radio-group>
			</view>
			<view class="cu-item shadow" v-if="bookingOrder.shippingMethod===1">
				<view class="cu-list menu menu-avatar">
					<view class="cu-item arrow">
						<view class="cu-avatar lg cuIcon-locationfill main-color"></view>
						<view class="content flex-sub padding-right" @click="toChooseAddress">
							<view v-if="selectAddress">{{selectAddress.consignee}} {{selectAddress.phone}}</view>
							<view v-if="selectAddress" class="text-gray flex justify-between">
								{{selectAddress.province}} {{selectAddress.city}} {{selectAddress.district}} {{selectAddress.address}}
							</view>
							<view v-else class="text-gray flex justify-between">请选择收货地址!</view>
						</view>
					</view>
				</view>
			</view>
			<view class="cu-item shadow" v-else>
				<view class="cu-list menu menu-avatar">
					<view class="cu-item">
						<view class="cu-avatar lg cuIcon-locationfill main-color"></view>
						<view class="content flex-sub padding-right">
							<view>{{shop.name}} {{shop.phone}}</view>
							<view class="text-gray flex justify-between">
								{{shop.address}}
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="cu-card case pro_card" v-for="(item,index) in bookingOrder.items" :key="index">
			<view class="cu-item shadow">
				<view class="cu-list menu-avatar">
					<view class="cu-item">
						<view class="cu-avatar">
							<image :src="item.url" mode="aspectFit"></image>
						</view>
						<view class="content flex-sub">
							<view>{{item.name}}</view>
							<view class="text-gray flex justify-between margin-top-10">
								{{item.speTitle}}
							</view>
							<view class="text-gray fr">￥{{item.price}}</view>
						</view>
					</view>
				</view>
				<view class="item_total">共{{item.buyCount}}件 小计:<text class="main-color">￥{{(item.price*item.buyCount).toFixed(2)}}</text></view>
			</view>
		</view>
		<view class="cu-card remark_card">
			<view class="cu-list menu">
				<view class="cu-item arrow" v-if="bookingOrder.shippingMethod===1">
					<view class="title">运费</view>
					<text class="main-color">{{productFreight>0?"￥"+productFreight:"免运费 包邮"}}</text>
				</view>
				<view class="cu-item arrow" @click="this.loadCoupon();this.isShowCoupon=!this.isShowCoupon">
					<view class="title">优惠卷</view>
					<text class="text-gray">{{couponTitle}}</text>
				</view>
			</view>
			<view class="cu-item shadow">
				<view class="title text-gray">订单备注</view>
				<view class="cu-form-group">
					<textarea maxlength="200" v-model="bookingOrder.remark" placeholder="选填,请先和商家协商一致"></textarea>
				</view>
			</view>
		</view>
		<view class="split-line margin-bottom-100"></view>
		<view class="split-line margin-bottom-100"></view>
		<view class="foot-bar">
			<view class="bg-white border tabbar shop">
				<view class="margin-right-20 text-right">
					<text class="margin-right-20">
						<text class="text-gray margin-right-10">共{{productCount}}件</text>
						<text class="text-bold text-xl">合计:</text>
						<text class="main-color">￥{{payPrice}}</text>
					</text>
					<button v-if="bookingOrder.items.length>0" :disabled="loading" class="cu-btn main-bg-color round shadow-blur lg" @click="submitOrder">提交订单</button>
				</view>
			</view>
		</view>

		<view class="cu-modal bottom-modal" :class="isShowCoupon ? 'show':'hide'" @click="this.isShowCoupon=false">
			<view class="cu-dialog" @click.stop="">
				<view class="coupon-list" v-if="couponList.length>0">
					 <radio-group @change="chooseCoupon">
						 <scroll-view scroll-y="true">
							<view class="scroll-view-item item stamp" :class="'stamp0'+(item.useRange+1)" v-for="(item,index) in couponList" :key="index">
								<view class="float-li t1">
									<view class="coupon-left">
										<view class="t t1">￥</view>
										<view class="t t2">{{item.discount}}</view>
										<view class="t t3">
											<view>
												{{item.rangeName}}<br/>满{{item.minimums}}减{{item.discount}}
											</view>
										</view>
										<view class="t t4">券码：{{item.code}}</view>
									</view>
								</view>
								<view class="float-li-rig">
									<view class="coupon-rig">
									   <view class="t1 t">有效期</view>
									   <view class="t2 t">{{item.startDate}}</view>
									   <view class="t2 t">{{item.endDate}}</view>									   
									   <view class="t3 t">
										   <checkbox class='round green' :checked="bookingOrder.couponId===item.id" :value="item.id"></checkbox>
									   </view>
									</view>
								</view>
								<i></i>
							</view>
						</scroll-view>
					 </radio-group>
				</view>
				<view v-else class="no_coupon">没有优惠卷哦!</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {CouponService} from "@/api/PromotionService.js"
	import {FreightService} from "@/api/ProductService.js"
	import {CartService,OrderService} from "@/api/OrderService.js"
	import {UserService} from "@/api/UserService.js"
	import {ShopService} from "@/api/ShopService.js"
	export default {
		data() {
			return {
				shop:undefined,shippingMethodForExpress:1,shippingMethodForSelf:4,loading:false,
				payPrice:0,productCount:0,couponList: [],isShowCoupon:false,couponTitle:"请选择优惠卷",productFreight:0,couponDiscount:0,selectAddress:undefined,
				bookingOrder:{items:[],remark:"",payType:2,shippingMethod:1,couponId:0,addressId:0,activityType:0,activityId:0}
			}
		},
		watch: {
			selectAddress(newVal, oldVal) {
				if(newVal){
					this.bookingOrder.addressId=newVal.id;
					this.loadOrderFreight();
				}
			},
			productFreight(newVal,oldVal){
				this.calculateOrderPayPrice();
			},
			couponDiscount(newVal,oldVal){
				this.calculateOrderPayPrice();
			}
		},
		onLoad(options) {
			const that=this;
			const eventChannel=that.getOpenerEventChannel();
			eventChannel.on('sendProducts', function(res) {
			    that.bookingOrder.items=res;
				that.bookingOrder.activityId=options.activityId;
				that.bookingOrder.activityType=options.activityType;
				that.calculateOrderProductCount();
				that.calculateOrderPayPrice();
			});
			this.loadDefaultAddress();
			this.loadShop();
		},
		onShow() {
			const that=this;
			uni.$on("chooseAddressEvent",function(res){
				that.selectAddress=res;
				that.bookingOrder.addressId=that.selectAddress.id;
				uni.$off("chooseAddressEvent");
			});
		},
		methods: {
			loadShop() {
				ShopService.getShop().then(res=>{
					this.shop=res;
				});
			},
			toChooseAddress() {
				uni.navigateTo({
					url: "../home/address/choose"
				});
			},
			loadDefaultAddress(){
				UserService.getDefaultAddress().then(res=>{
					this.selectAddress=res;
				});
			},
			loadCoupon(){
				CouponService.getUserCoupons(1).then(res=>{
					this.couponList=res;
				});
			},
			chooseCoupon(e){
				const cId=e.detail.value;
				const that=this;
				if(!cId){
					that.bookingOrder.couponId=0;
					that.couponDiscount=0;
					that.isShowCoupon=false;
					that.couponTitle="请选择优惠卷";
					return;
				}
				const couponId=parseInt(e.detail.value);
				that.bookingOrder.couponId=couponId;
				CartService.getOrderCouponDiscount(that.bookingOrder).then(res=>{
					that.isShowCoupon=false;
					that.couponTitle="请选择优惠卷";
					that.couponList.forEach(coupon=>{
						if(coupon.id===couponId){
							that.couponTitle="满"+coupon.minimums+"元立减"+coupon.discount+"元卷";
							that.couponDiscount=coupon.discount;
						}
					});
				},err=>{
					that.bookingOrder.couponId=0;
				});
			},
			loadOrderFreight(){
				CartService.getOrderFreight(this.bookingOrder).then(res=>{
					this.productFreight=parseFloat(res);
				});
			},
			chooseShpping(e){
				this.bookingOrder.shippingMethod=parseInt(e.detail.value);
				if(this.bookingOrder.shippingMethod===this.shippingMethodForExpress){
					if(this.selectAddress){
						this.loadOrderFreight();
					}
				}else if(this.bookingOrder.shippingMethod===this.shippingMethodForSelf){
					this.productFreight=0;
				}
			},
			calculateOrderProductCount(){
				this.productCount = this.bookingOrder.items.reduce((total,item)=>{
					return total+item.buyCount
				},0);
			},
			calculateOrderPayPrice(){
				this.payPrice=0;
				this.bookingOrder.items.forEach(item=>{
					this.payPrice+=item.price*item.buyCount;
				});
				this.payPrice+=this.productFreight;
				this.payPrice=this.payPrice-this.couponDiscount;
				this.payPrice=this.payPrice.toFixed(2);
			},
			getOrderTradeStatus(orderNo){
				return new Promise(function(resolve,reject){
					OrderService.getOrderTradeStatus(orderNo).then(res=>{
						resolve(res);
					});
				});
			},
			submitOrder(){
				if(this.bookingOrder.shippingMethod===this.shippingMethodForExpress){
					if(this.bookingOrder.addressId===0){
						uni.showToast({icon:"none",title:"请选择收货地址!"});
						return;
					}
				}
				const that=this;
				that.loading = true;
				OrderService.payTemplates().then(ids=>{
					uni.requestSubscribeMessage({tmplIds:ids,complete:function(){
						OrderService.bookingOrder(that.bookingOrder).then((orderNo)=>{
							// 发起支付
							OrderService.payOrder(orderNo).then(res=>{
								uni.requestPayment({
									paySign:res.paySign,nonceStr:res.nonceStr,package:res.package,
									timeStamp:res.timeStamp,signType:res.signType,provider:res.provider,
									success:function(res){
										let options={};
										options={icon:"success",title:"支付成功!"};
										options.success=function(){
											setTimeout(function(){
												uni.redirectTo({
													url:"/pages/home/order/detail?orderNo="+orderNo
												});											
											},2000);
										}
										uni.showToast(options);
									},
									fail:function(err){
										uni.redirectTo({url:"/pages/home/order/detail?orderNo="+orderNo});
									},
									complete:function(){
										that.loading = false;
									}
								})
							});
						});
					}});
				});
			}
		}
	}
</script>
<style lang="scss">
	page {background: #f1f1f1 !important;}

	.ship {padding: 20rpx;}

	.cu-list {
		.cu-item {
			height: 180rpx !important;

			.cu-avatar {
				background: none !important;
			}
		}
	}

	.pro_card {
		.cu-list {
			padding: 30rpx 10rpx !important;
			.cu-item {
				height: auto !important;
				&:after {
					transform-origin: unset !important
				}
			}
		}

		.cu-list:nth-child(1) {
			padding-bottom: 0 !important;
		}

		.cu-list:nth-child(2) {
			padding: 0 !important;

			.cu-item {
				height: unset !important;
			}
		}

		.item_total {
			text-align: right;
			margin: 30rpx;
		}

		.cu-avatar {
			width: 180rpx;
			height: 180rpx;
			left: 0rpx !important;
			position: relative !important;
		}

		.content {
			margin-left: 20rpx;
			position: relative !important;
			left: 0rpx !important;
		}
	}

	.remark_card {
		.title {
			padding: 30rpx;
		}
		.cu-list {
			margin: 30rpx;
			.cu-item {
			    height: 50rpx !important;
			}
		}
	}

	.foot-bar {
		position: fixed;
		width: 100%;
		bottom: 0;
		z-index: 1000;
		.tabbar {
			padding: 20rpx;
		}
	}
	.no_coupon{margin: 20% 0;}
	radio-group{width: 100%};
	.coupon-list{height:450px;display: flex;overflow: auto;}
	.float-li-rig{position:absolute;right:0;z-index:1000;}
</style>
